﻿using CustomBA.HelpClass;
using CustomBA.Models;
using CustomBA.ViewModels;
using CustomBA.Views;
using Microsoft.Tools.WindowsInstallerXml.Bootstrapper;
using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Security;
using System.Windows;
using System.Windows.Threading;

namespace CustomBA
{
	public class CustomBootstrapperApplication : BootstrapperApplication
	{
		public static Dispatcher Dispatcher { get; set; }
		protected override void Run()
		{
			// MessageBox.Show("test");
			Dispatcher = Dispatcher.CurrentDispatcher;
			var model = BootstrapperApplicationModel.GetBootstrapperAppModel(this);
			var view = new InstallView();
			this.Engine.Detect();
			BootstrapperApplicationModel.isUninstall = Command.Action == LaunchAction.Uninstall;
			if (Command.Action == LaunchAction.Uninstall && (Command.Display == Display.None || Command.Display == Display.Embedded))
			{
				// RegeditHelper.Instance.RemoveVersionReg();
				model.PlanAction(LaunchAction.Uninstall);
				Engine.Quit(model.FinalResult);
				return;
			}
			else if (Command.Action == LaunchAction.Install && (Command.Display == Display.None || Command.Display == Display.Embedded))
			{
				string installFolder = RegeditHelper.Instance.GetInstallPathReg();
				if (installFolder == null || installFolder == "")
				{
					installFolder = RegeditHelper.Instance.GetFirstUsefulDrive() + @"Program Files\jinzhangshu\IntoTheVoid";
				}

				var path = Engine.StringVariables["ReInstallPath"];
				if(path != null || path != "")
				{
					installFolder = path;
				}

				model.SetBurnVariable("InstallFolder", installFolder);
				(view.DataContext as InstallViewModel).State = InstallState.Applying;
				model.PlanAction(LaunchAction.Install);
			}
			else if (Command.Action == LaunchAction.Uninstall)
			{
				(view.DataContext as InstallViewModel).State = InstallState.Present;
			}

			var oldVersion = RegeditHelper.Instance.GetInstalledVersionReg();
			var version = model.GetCurrentVersion();
			if ((oldVersion != "" || oldVersion != null) &&
				(!RegeditHelper.Instance.VersionIsNewer(oldVersion, version)) &&
				Command.Action == LaunchAction.Install)
			// if(Command.Action == LaunchAction.Install)
			{
				BootstrapperApplicationModel.isReInstall = true;
			}

			model.SetWindowHandle(view);
			view.Show();
			Dispatcher.Run();
			Engine.Quit(model.FinalResult);
		}

	}
}
